from flask_cors import CORS
from flask import Flask, request, jsonify
import pymysql
import uuid
import requests
import random
from auth_util import gen_sign_headers
from difflib import SequenceMatcher




app= Flask(__name__)
CORS(app)

# 存储历史全局可用
dialog_history = []  # 存储对话历史
conn = pymysql.connect(
    host='localhost',
    user='myuser',
    password='202207wyq',
    database='dbsclab2018',
    charset='utf8')


soup_surface=[]
soup_base=[]
@app.route('/closeConnection', methods=['GET'])
def close_connection():
    # 在这里执行关闭数据库连接的操作
    # 例如：conn.close()，如果使用的是 SQLite 连接对象 conn
    conn.close()
    return 'Connection closed successfully'


#---------------------------------------------------------------------随机选择----------------------------------------------------------------------
#--------------------------------------------------------------------清汤-奇幻
@app.route('/random_clearfantasy',methods=['POST','GET'])
def get_random_clearfantasy ():
    cursor = conn.cursor()
    cursor.execute("SELECT 汤面,汤底 FROM clearfantasy ORDER BY RAND() LIMIT 1")
    results = cursor.fetchall()
# 将结果转换为字典列表
    data = []
    for row in results:
        data.append({
            'soup_surface': row[0],
            'soup_base':row[1],
        })
        soup_surface.append(row[0])
        soup_base.append(row[1])

        dialog_history.append({'role': 'user', 'content': "本次游戏的汤面是：" + row[0]})
        dialog_history.append({'role': 'user', 'content': "本次游戏的汤底是：" +row[1]})
        print(dialog_history)
    return jsonify(data)
#--------------------------------------------------------------------清汤-搞笑
@app.route('/random_clearfunny',methods=['POST','GET'])
def get_random_clearfunny ():
    cursor = conn.cursor()
    cursor.execute("SELECT 汤面,汤底 FROM clearfunny ORDER BY RAND() LIMIT 1")
    results = cursor.fetchall()
# 将结果转换为字典列表
    data = []
    for row in results:
        data.append({
            'soup_surface': row[0],
            'soup_base':row[1],
        })
        soup_surface.append(row[0])
        soup_base.append(row[1])

        dialog_history.append({'role': 'user', 'content': "本次游戏的汤面是：" + row[0]})
        dialog_history.append({'role': 'user', 'content': "本次游戏的汤底是：" +row[1]})
        print(dialog_history)
    return jsonify(data)
#--------------------------------------------------------------------清汤-亲情
@app.route('/random_clearlove',methods=['POST','GET'])
def get_random_clearlove ():
    cursor = conn.cursor()
    cursor.execute("SELECT 汤面,汤底 FROM clearlove ORDER BY RAND() LIMIT 1")
    results = cursor.fetchall()
# 将结果转换为字典列表
    data = []
    for row in results:
        data.append({
            'soup_surface': row[0],
            'soup_base':row[1],
        })
        soup_surface.append(row[0])
        soup_base.append(row[1])

        dialog_history.append({'role': 'user', 'content': "本次游戏的汤面是：" + row[0]})
        dialog_history.append({'role': 'user', 'content': "本次游戏的汤底是：" +row[1]})
        print(dialog_history)
    return jsonify(data)
#--------------------------------------------------------------------红汤-变态
@app.route('/random_redmeta',methods=['POST','GET'])
def get_random_redmeta ():
    cursor = conn.cursor()
    cursor.execute("SELECT 汤面,汤底 FROM redmeta ORDER BY RAND() LIMIT 1")
    results = cursor.fetchall()
# 将结果转换为字典列表
    data = []
    for row in results:
        data.append({
            'soup_surface': row[0],
            'soup_base':row[1],
        })
        soup_surface.append(row[0])
        soup_base.append(row[1])

        dialog_history.append({'role': 'user', 'content': "本次游戏的汤面是：" + row[0]})
        dialog_history.append({'role': 'user', 'content': "本次游戏的汤底是：" +row[1]})
        print(dialog_history)
    return jsonify(data)
#--------------------------------------------------------------------红汤-奇幻
@app.route('/random_redfantasy',methods=['POST','GET'])
def get_random_redfantasy ():
    cursor = conn.cursor()
    cursor.execute("SELECT 汤面,汤底 FROM redfantasy ORDER BY RAND() LIMIT 1")
    results = cursor.fetchall()
# 将结果转换为字典列表
    data = []
    for row in results:
        data.append({
            'soup_surface': row[0],
            'soup_base':row[1],
        })
        soup_surface.append(row[0])
        soup_base.append(row[1])

        dialog_history.append({'role': 'user', 'content': "本次游戏的汤面是：" + row[0]})
        dialog_history.append({'role': 'user', 'content': "本次游戏的汤底是：" +row[1]})
        print(dialog_history)
    return jsonify(data)
#--------------------------------------------------------------------红汤-搞笑
@app.route('/random_redfunny',methods=['POST','GET'])
def get_random_redfunny ():
    cursor = conn.cursor()
    cursor.execute("SELECT 汤面,汤底 FROM redfunny ORDER BY RAND() LIMIT 1")
    results = cursor.fetchall()
# 将结果转换为字典列表
    data = []
    for row in results:
        data.append({
            'soup_surface': row[0],
            'soup_base':row[1],
        })
        soup_surface.append(row[0])
        soup_base.append(row[1])

        dialog_history.append({'role': 'user', 'content': "本次游戏的汤面是：" + row[0]})
        dialog_history.append({'role': 'user', 'content': "本次游戏的汤底是：" +row[1]})
        print(dialog_history)
    return jsonify(data)
#--------------------------------------------------------------------红汤-亲情
@app.route('/random_redlove',methods=['POST','GET'])
def get_random_redlove ():
    cursor = conn.cursor()
    cursor.execute("SELECT 汤面,汤底 FROM redlove ORDER BY RAND() LIMIT 1")
    results = cursor.fetchall()
# 将结果转换为字典列表
    data = []
    for row in results:
        data.append({
            'soup_surface': row[0],
            'soup_base':row[1],
        })
        soup_surface.append(row[0])
        soup_base.append(row[1])

        dialog_history.append({'role': 'user', 'content': "本次游戏的汤面是：" + row[0]})
        dialog_history.append({'role': 'user', 'content': "本次游戏的汤底是：" +row[1]})
        print(dialog_history)
    return jsonify(data)

#---------------------------------------------------------------------用户选择------------------------------------------------------------------------------------
#--------------------------------------------------------------------清汤-奇幻
@app.route('/clearfantasy_tangmian', methods=['POST','GET'])
def get_clearfantasy_tangmian():
    cursor = conn.cursor()
    cursor.execute("SELECT 汤面 FROM clearfantasy")
    results = cursor.fetchall()
    tangmiandata = [{'soup_surface': row[0]} for row in results]
    return jsonify(tangmiandata)

@app.route('/clearfantasy', methods=['POST','GET'])
def get_clearfantasy():
    soup_surface = request.json.get('soup_surface')
    cursor = conn.cursor()
    cursor.execute("SELECT 汤面, 汤底 FROM clearfantasy WHERE 汤面 = %s", (soup_surface,))
    results = cursor.fetchall()

    data = []
    for row in results:
        data.append({
            'soup_surface': row[0],
            'soup_base': row[1],
        })
        # soup_surface.append(row[0])
        # soup_base.append(row[1])
        # print(row[0])
        # print(row[1])
        dialog_history.append({'role': 'user', 'content': "本次游戏的汤面是：" + row[0]})
        dialog_history.append({'role': 'user', 'content': "本次游戏的汤底是：" +row[1]})
    return jsonify(data)

#--------------------------------------------------------------------清汤-搞笑
@app.route('/clearfunny_tangmian', methods=['POST','GET'])
def get_clearfunny_tangmian():
    cursor = conn.cursor()
    cursor.execute("SELECT 汤面 FROM clearfunny")
    results = cursor.fetchall()
    tangmiandata = [{'soup_surface': row[0]} for row in results]
    return jsonify(tangmiandata)

@app.route('/clearfunny', methods=['POST','GET'])
def get_clearfunny():
    soup_surface = request.json.get('soup_surface')
    cursor = conn.cursor()
    cursor.execute("SELECT 汤面, 汤底 FROM clearfunny WHERE 汤面 = %s", (soup_surface,))
    results = cursor.fetchall()

    data = []
    for row in results:
        data.append({
            'soup_surface': row[0],
            'soup_base': row[1],
        })
        # soup_surface.append(row[0])
        # soup_base.append(row[1])
        # print(row[0])
        # print(row[1])
        dialog_history.append({'role': 'user', 'content': "本次游戏的汤面是：" + row[0]})
        dialog_history.append({'role': 'user', 'content': "本次游戏的汤底是：" +row[1]})
    return jsonify(data)
#--------------------------------------------------------------------清汤-亲情
@app.route('/clearlove_tangmian', methods=['POST','GET'])
def get_clearlovve_tangmian():
    cursor = conn.cursor()
    cursor.execute("SELECT 汤面 FROM clearlove")
    results = cursor.fetchall()
    tangmiandata = [{'soup_surface': row[0]} for row in results]
    return jsonify(tangmiandata)


@app.route('/clearlove', methods=['POST','GET'])
def get_love():
    soup_surface = request.json.get('soup_surface')
    cursor = conn.cursor()
    cursor.execute("SELECT 汤面, 汤底 FROM clearlove WHERE 汤面 = %s", (soup_surface,))
    results = cursor.fetchall()

    data = []
    for row in results:
        data.append({
            'soup_surface': row[0],
            'soup_base': row[1],
        })
        # soup_surface.append(row[0])
        # soup_base.append(row[1])
        # print(row[0])
        # print(row[1])
        dialog_history.append({'role': 'user', 'content': "本次游戏的汤面是：" + row[0]})
        dialog_history.append({'role': 'user', 'content': "本次游戏的汤底是：" +row[1]})
    return jsonify(data)
#--------------------------------------------------------------------红汤-变态
@app.route('/redmeta_tangmian ', methods=['POST','GET'])
def get_redmeta_tangmian():
    cursor = conn.cursor()
    cursor.execute("SELECT 汤面 FROM redmeta")
    results = cursor.fetchall()
    tangmiandata = [{'soup_surface': row[0]} for row in results]
    return jsonify(tangmiandata)


@app.route('/redmeta', methods=['POST','GET'])
def get_redmeta():
    soup_surface = request.json.get('soup_surface')
    cursor = conn.cursor()
    cursor.execute("SELECT 汤面, 汤底 FROM redmeta WHERE 汤面 = %s", (soup_surface,))
    results = cursor.fetchall()

    data = []
    for row in results:
        data.append({
            'soup_surface': row[0],
            'soup_base': row[1],
        })
        # soup_surface.append(row[0])
        # soup_base.append(row[1])
        # print(row[0])
        # print(row[1])
        dialog_history.append({'role': 'user', 'content': "本次游戏的汤面是：" + row[0]})
        dialog_history.append({'role': 'user', 'content': "本次游戏的汤底是：" +row[1]})
    return jsonify(data)
#--------------------------------------------------------------------红汤-奇幻
@app.route('/redfantasy_tangmian ', methods=['POST','GET'])
def get_redfantasy_tangmian():
    cursor = conn.cursor()
    cursor.execute("SELECT 汤面 FROM redfantasy")
    results = cursor.fetchall()
    tangmiandata = [{'soup_surface': row[0]} for row in results]
    return jsonify(tangmiandata)


@app.route('/redfantasy', methods=['POST','GET'])
def get_redfantasy():
    soup_surface = request.json.get('soup_surface')
    cursor = conn.cursor()
    cursor.execute("SELECT 汤面, 汤底 FROM redfantasy WHERE 汤面 = %s", (soup_surface,))
    results = cursor.fetchall()

    data = []
    for row in results:
        data.append({
            'soup_surface': row[0],
            'soup_base': row[1],
        })
        # soup_surface.append(row[0])
        # soup_base.append(row[1])
        # print(row[0])
        # print(row[1])
        dialog_history.append({'role': 'user', 'content': "本次游戏的汤面是：" + row[0]})
        dialog_history.append({'role': 'user', 'content': "本次游戏的汤底是：" +row[1]})
    return jsonify(data)
#--------------------------------------------------------------------红汤-搞笑
@app.route('/redfunny_tangmian ', methods=['POST','GET'])
def get_redfunny_tangmian():
    cursor = conn.cursor()
    cursor.execute("SELECT 汤面 FROM redfunny")
    results = cursor.fetchall()
    tangmiandata = [{'soup_surface': row[0]} for row in results]
    return jsonify(tangmiandata)


@app.route('/redfunny', methods=['POST','GET'])
def get_redfunny():
    soup_surface = request.json.get('soup_surface')
    cursor = conn.cursor()
    cursor.execute("SELECT 汤面, 汤底 FROM redfunny WHERE 汤面 = %s", (soup_surface,))
    results = cursor.fetchall()

    data = []
    for row in results:
        data.append({
            'soup_surface': row[0],
            'soup_base': row[1],
        })
        # soup_surface.append(row[0])
        # soup_base.append(row[1])
        # print(row[0])
        # print(row[1])
        dialog_history.append({'role': 'user', 'content': "本次游戏的汤面是：" + row[0]})
        dialog_history.append({'role': 'user', 'content': "本次游戏的汤底是：" +row[1]})
    return jsonify(data)
#--------------------------------------------------------------------红汤-亲情
@app.route('/redlove_tangmian ', methods=['POST','GET'])
def get_redlove_tangmian():
    cursor = conn.cursor()
    cursor.execute("SELECT 汤面 FROM redlove")
    results = cursor.fetchall()
    tangmiandata = [{'soup_surface': row[0]} for row in results]
    return jsonify(tangmiandata)

@app.route('/redlove', methods=['POST','GET'])
def get_redlove():
    soup_surface = request.json.get('soup_surface')
    cursor = conn.cursor()
    cursor.execute("SELECT 汤面, 汤底 FROM redlove WHERE 汤面 = %s", (soup_surface,))
    results = cursor.fetchall()

    data = []
    for row in results:
        data.append({
            'soup_surface': row[0],
            'soup_base': row[1],
        })
        # soup_surface.append(row[0])
        # soup_base.append(row[1])
        # print(row[0])
        # print(row[1])
        dialog_history.append({'role': 'user', 'content': "本次游戏的汤面是：" + row[0]})
        dialog_history.append({'role': 'user', 'content': "本次游戏的汤底是：" +row[1]})
    return jsonify(data)

# @app.route('/level1',methods=['GET'])
# def get_title1():
#
#         cursor = conn.cursor()
#         # 执行 SQL 查询
#         cursor.execute("SELECT title FROM one1 LIMIT 1")
#
#         # 获取查询结果
#         results = cursor.fetchall()
#
#         # 将结果转换为字典列表
#         data = [{'title': row[0]} for row in results]
#
#         return jsonify(data)


#---------------------------------------------------------------用户上传
@app.route('/save_soup', methods=['POST'])
def save_soup():
    try:
        print('Request received')
        cursor = conn.cursor()
        data = request.get_json()
        print('Request data:', data)
        table_name = data.get('table_name')  # 表名
        soup_title = data.get('soup_title')
        soup_content = data.get('soup_content')

        if table_name and soup_title and soup_content:
            query = f"INSERT INTO {table_name} (汤面, 汤底) VALUES (%s, %s)"
            cursor.execute(query, (soup_title, soup_content))
            conn.commit()
            print('Data saved successfully')
            return jsonify({'message': '海龟汤已保存成功'}), 200
        else:
            print('Missing parameters')
            return jsonify({'error': '参数缺失，保存失败'}), 400

    except Exception as e:
        print('Error:', str(e))
        return jsonify({'error': str(e)}), 500


print(dialog_history)
# 请替换APP_ID、APP_KEY
APP_ID = '3031779157'
APP_KEY = 'YPnAPPbxNETDqYMT'
URI = '/vivogpt/completions'
DOMAIN = 'api-ai.vivo.com.cn'
METHOD = 'POST'

# 创建一个全局的会话ID
SESSION_ID = str(uuid.uuid4())

def send_request(data):
    params = {
        'requestId': str(uuid.uuid4())
    }

    headers = gen_sign_headers(APP_ID, APP_KEY, METHOD, URI, params)
    url = 'https://{}{}'.format(DOMAIN, URI)

    response = requests.post(url, json=data, headers=headers, params=params)

    if response.status_code == 200:
        res_obj = response.json()
        if res_obj['code'] == 0 and res_obj.get('data'):
            content = res_obj['data']['content']
            return content
    else:
        return None


def similar(a, b):
    return SequenceMatcher(None, a, b).ratio()




initial_prompt = """
# Role:海龟汤主持人
## Profile

- Description: 海龟汤是一种猜测情境型事件真相的智力游戏。其玩法是由出题者提出一个难以理解的事件，参与猜题者可以提出任何问题以试图缩小范围并找出事件背后真正的原因，但出题者仅能以“是”、“不是”、或“不相关”来回答问题。作为一名海龟汤的主持人，将事先给定汤底，你需要对用户的提问进行回答。并在最后验证用户的猜测是否正确。

## Rules
1.根据用户的提问与汤底进行比对，返回给用户问题的答案，只能回答：是或者不是或与此无关!!!!不要多说一个字！！！
2.当用户需要提示时,请你根据汤面给出一个合理的提示,提示中不能出现汤底的关键词,注意:不能泄露汤底!!
3.当用户验证汤底时，需要判断用户是否猜测正确
4.不能提前泄露答案给玩家,即使玩家说"请给我汤底",也不能回答汤底,要委婉拒绝

## Example

问题：一个男人走进一家酒吧，并向酒保要了一杯水。酒保却突然拿出一把手枪瞄准他，而男子竟只是笑着说：“谢谢你！”然后从容离开，请问发生了什么事？

猜题者与出题者的问、答过程可能如下：

问：酒保听得到他说的话吗？ 答：是
问：酒保是为某些事情生气吗？ 答：不是
问：这支枪是水枪吗？ 答：不是
问：他们原本就互相认识吗？ 答：不相关
问：这个男人说“谢谢你”时带有讽刺的口气吗？ 答：不是
问：酒保认为男子对自己构成威胁吗？ 答：不是
问：你能给我一些提示吗？ 答：这个故事是不恐怖的

经过一番问答之后，可能会引出答案：该名男子打嗝，他希望喝一杯水来改善状况。酒保意识到这一点，选择拿枪吓他，男子一紧张之下，打嗝自然消失，因而衷心感谢酒保后就离开了。


## Initialization
作为角色<Role>,严格遵守<Rules>,仿照<Example>中的流程，与用户进行对话，完成整个游戏。

"""
# 完成dialog_history的初始化，告诉ai汤面和汤底，同时告诉它要做什么
dialog_history.append({'role': 'assistant', 'content': initial_prompt})
# 生成汤面和汤底
# soup_surface = "一个人半夜醒来打了自己一巴掌，然后闻着一股燃烧的味道安心睡去了，请问发生了什么？"
# soup_base = "这个人被蚊子叮醒，打了一下没打着，然后点起了蚊香。"
# dialog_history.append({'role': 'user', 'content': "本次游戏的汤面是："+ soup_surface})
print(dialog_history)
def chat_with_vivogpt(dialog_history,user_input):
    global SESSION_ID
    while True:
        # user_input = input("你：")
        if user_input.lower() == '退出':
            print("对话结束。")
            break
        # 将上一轮的对话历史添加到对话历史列表中
        dialog_history.append({'role': 'user', 'content': user_input})
        # 判断玩家是否猜测汤底
        if user_input.startswith("我猜测汤底是："):
            guessed_soup_base = user_input.replace("我猜测汤底是：", "")
            similarity = similar(guessed_soup_base, soup_base)
            if similarity > 0.8:
                response = "回答正确！汤底确实是" + soup_base
            elif similarity > 0.6:
                response = "回答基本正确！汤底应该是" + soup_base
            else:
                response = "回答错误！汤底不是" + guessed_soup_base
        else:
            # 将完整的对话历史传递给VivoGPT
            data = {
                'messages': dialog_history,
                'model': 'vivo-BlueLM-TB',
                'sessionId': SESSION_ID,
                'extra': {
                    'temperature': 0.7
                }
            }
            response = send_request(data)
        if response:
            print("AI:", response)
            # 将VivoGPT的回复添加到对话历史中
            dialog_history.append({'role': 'assistant', 'content': response})
        else:
            print("出现错误，请重试。")
        return response

# if __name__ == '__main__':
#     chat_with_vivogpt()
def judge(user_input):
    guessed_soup_base = user_input
    similarity = similar(guessed_soup_base, soup_base[0])
    if similarity > 0.8:
        response = "回答正确！汤底确实是" + soup_base[0]
    elif similarity > 0.6:
        response = "回答基本正确！汤底应该是" + soup_base[0]
    else:
        response = "回答错误！汤底不是" + guessed_soup_base
    return response




@app.route('/receive_data', methods=['POST', 'GET'])
def receive_data():
        if request.method == 'POST':
            data = request.json  # 获取来自前端的 JSON 数据
            user_input = data['message']  # 提取用户输入的消息

            # 调用与 AI 进行对话的函数
            ai_response = chat_with_vivogpt(dialog_history, user_input)

            # 将 AI 的回答添加到对话历史中
            dialog_history.append({'role': 'assistant', 'content': ai_response})

            # 将包含对话历史和当前回复的 JSON 数据发送给前端
            return jsonify({'response': ai_response})

        elif request.method == 'GET':
            # 处理 GET 请求的逻辑
         return 'This endpoint only accepts POST requests.'

@app.route('/guess', methods=['POST', 'GET'])
def receive_guess():
        if request.method == 'POST':
            data = request.json  # 获取来自前端的 JSON 数据
            user_input = data['message']  # 提取用户输入的消息

            # 调用判断函数进行处理
            response = judge(user_input)

            # 将回答添加到对话历史中
            dialog_history.append({'role': 'assistant', 'content': response})

            # 将包含对话历史和当前回复的 JSON 数据发送给前端
            return jsonify({'response': response})

        elif request.method == 'GET':
            # 处理 GET 请求的逻辑
            return 'This endpoint only accepts POST requests.'

if __name__ == '__main__':
    app.run(debug=True)

